from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from app.models.user import User, Address
# 引入result.py中定义的数据类型转换工具类和方法
from app.util.result import model_to_dict, CodeModeDTO, query_set_to_list
from django.views.decorators.http import require_http_methods
import json


# Create your views here.

@require_http_methods(["POST", "GET"])
def query_by_id(request):
	"""
	根据用户id,判断登录用户uid和oid是否匹配
	:param request: 数据请求
	:return: json
	"""
	id = request.GET.get('id', "")
	cname = request.GET.get('cname', "")
	if id is not "" and cname is not "":
		user = User.objects.get(id=id)
		add = user.addresses
		for a in add:
			if a.c_name == cname:
				print(a)
				aa = model_to_dict(a)
	# users = model_to_dict(user)
	# 转化为实体
	# users = model_to_dict(user)

	"""
	规范接口返回格式 即CodeModeDTO（code,message,data）
	 :param code: int 返回码
	 :param message: string 返回消息
	 :param data: obj 返回的数据
	"""
	user_json = CodeModeDTO(CodeModeDTO.SUCCESS, '查询成功', aa)
	return HttpResponse(user_json.to_json(), content_type='application/json,charset=utf-8')


# 显示收货地址
@csrf_exempt
@require_http_methods(["POST", "GET"])
def add_address(request):
	"""
	添加用户收货地址并回显该地址
	:param request:数据请求
	:return: json
	"""
	# id = '5ba9f3baade2b827c4f39513'
	id = request.GET.get('id')
	user = User.objects.get(id=id)  # 测试用数据
	Suinfo = json.loads(request.body.decode('utf-8'))
	address = Address()
	address["room_number"] = Suinfo["room_number"]
	address["consignee"] = Suinfo["consignee"]
	address["phone_number"] = Suinfo["phone_number"]
	# address["c_name"] = Suinfo["cname"]
	address["p_name"] = Suinfo["pname"]
	address["point_address"] = Suinfo["point_address"]
	cname = Suinfo["cname"]
	adds = user.addresses
	code = 1
	for a in adds:
		if a.c_name == cname:
			code = 0
		else:
			code = 1
	if code == 1:
		address["c_name"] = cname
		user.addresses.append(address)
		user.save()
		# # 获取收货地址下标
		# i = len(user.addresses) - 1
		# # 根据下标获取收货地址信息
		# add = user.addresses[i]
		# 转化为实体
		users = model_to_dict(user)
		# 存储下标值
		# users["xb"] = i
		"""
		规范接口返回格式 即CodeModeDTO（code,message,data）
		 :param code: int 返回码
		 :param message: string 返回消息
		 :param data: obj 返回的数据
		"""
		user_json = CodeModeDTO(CodeModeDTO.SUCCESS, '添加成功', users)
		return HttpResponse(user_json.to_json(), content_type='application/json,charset=utf-8')
	user_json = CodeModeDTO(CodeModeDTO.SUCCESS, '社区已存在', '')
	return HttpResponse(user_json.to_json(), content_type='application/json,charset=utf-8')


@csrf_exempt
def update_by_id(request):
	"""
	根据用户id和收货地址下标更新用户的地址等信息
	:param request: 数据请求
	:return: json
	"""
	id = request.GET.get('id', '')
	user = User.objects.get(id=id)  # 测试用数据
	Suinfo = json.loads(request.body.decode('utf-8'))
	cname = Suinfo["cname"]
	for a in user.addresses:
		if a.c_name == cname:
			# 更新收货地址
			a.room_number = Suinfo["room_number"]  # 房间号
			a.consignee = Suinfo["consignee"]  # 收货人
			a.phone_number = Suinfo["phone_number"]  # 联系电话
			a.c_name = Suinfo["cname"]
			a.p_name = Suinfo["pname"]
			a.point_address = Suinfo["point_address"]
			user.save()
	# user.save()
	# 转化为实体
	users = model_to_dict(user)
	"""
	规范接口返回格式 即CodeModeDTO（code,message,data）
	 :param code: int 返回码
	 :param message: string 返回消息
	 :param data: obj 返回的数据
	"""
	user_json = CodeModeDTO(CodeModeDTO.SUCCESS, '更新成功', users)
	return HttpResponse(user_json.to_json(), content_type='application/json,charset=utf-8')


def address_list(request):
	# id = request.GET.get('id')
	id = '5ba9f3baade2b827c4f39513'
	user = User.objects.get(id=id)  # 测试用数据
	# 获取收货地址列表
	addressList = user.addresses
	# 转化为实体
	users = query_set_to_list(addressList)
	"""
	规范接口返回格式 即CodeModeDTO（code,message,data）
	 :param code: int 返回码
	 :param message: string 返回消息
	 :param data: obj 返回的数据
	"""
	user_json = CodeModeDTO(CodeModeDTO.SUCCESS, '查询成功', users)
	return HttpResponse(user_json.to_json(), content_type='application/json,charset=utf-8')


def show(request):
	"""
	判断是否显示添加收货地址的弹框
	:param request:数据请求
	:return: json
	"""
	id = request.GET.get('id', '')
	cname = request.GET.get('cname', '')
	try:
		user = User.objects.get(id=id)  # 测试用数据
	except User.DoesNotExist:
		pass
	# 获取收货地址列表
	if len(user.addresses) == 0:
		# 转化为实体
		user = model_to_dict(user)
		# 存储是否显示标志值，1是显示，0是不显示
		user["show"] = 1
	elif len(user.addresses) != 0:
		if User.objects.filter(id=id).filter(addresses__c_name=cname):
			user = model_to_dict(user)
			user["show"] = 0
		else:
			user = model_to_dict(user)
			user["show"] = 1
	else:
		# 转化为实体
		user = model_to_dict(user)
		user["show"] = 0
	"""
	规范接口返回格式 即CodeModeDTO（code,message,data）
	 :param code: int 返回码
	 :param message: string 返回消息
	 :param data: obj 返回的数据
	"""
	user_json = CodeModeDTO(CodeModeDTO.SUCCESS, '查询成功', user)
	return HttpResponse(user_json.to_json(), content_type='application/json,charset=utf-8')